//
//  DirtyRectanglesView.m
//  CoreAnimation
//
//  Created by 张国文 on 16/11/2.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "DirtyRectanglesView.h"
#define kBrushWidth 16

@interface DirtyRectanglesView ()

@property (nonatomic, strong) NSMutableArray *strokePointArray; // 画笔的记录点

@end

@implementation DirtyRectanglesView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.strokePointArray = [NSMutableArray array];
        //  [self.layer drawsAsynchronously];
        self.layer.shouldRasterize = YES;
    }
    return self;
}

- (void)addPointToStrokePointArrayWithPoint:(CGPoint)point
{
    [self.strokePointArray addObject:[NSValue valueWithCGPoint:point]];
 //   [self setNeedsDisplay]; // 这个是整屏绘制，会造成浪费
    [self setNeedsDisplayInRect:[self getBrushRectForPoint:point]]; // 局域绘制，对指定的区域进行刷新，已经绘制出来的点不需地方重新绘制，我们只需要重绘新加入的点，因此如果每次都整个屏幕刷新的话，会造成浪费，并且对CPU和GPU造成负担

}

- (CGRect)getBrushRectForPoint:(CGPoint)point
{
    return CGRectMake(point.x - kBrushWidth / 2, point.y - kBrushWidth / 2, kBrushWidth, kBrushWidth);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint point = [[touches anyObject] locationInView:self];
    [self addPointToStrokePointArrayWithPoint:point];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CGPoint point = [[touches anyObject] locationInView:self];
    [self addPointToStrokePointArrayWithPoint:point];
}

- (void)drawRect:(CGRect)rect
{
  
    // 这个是整屏绘制的逻辑
//    for (int i = 0; i < self.strokePointArray.count; i++) {
//        CGPoint tempPoint = [self.strokePointArray[i] CGPointValue];
//        // 围绕这个点构造矩形
//        CGRect rect = CGRectMake(tempPoint.x - kBrushWidth / 2, tempPoint.y - kBrushWidth, kBrushWidth, kBrushWidth);
//        [[UIImage imageNamed:@"whiteBrush"] drawInRect:rect];
//    }
//    NSLog(@"rect = %@", [NSValue valueWithCGRect:rect]);
    // 这个是指定区域绘制的逻辑，我们运用这个方法仍然会造成不必要的内存浪费，原因是因为在指定的刷新点仍然会循环self.strokePointArray的次数，但是相较于整屏刷新这种方法对CPU和GPU的负担已经很小了。如果您有什么好的解决办法的话，可以我和交流一下。
    for (int i = 0; i < self.strokePointArray.count; i++) {
        CGPoint tempPoint = [self.strokePointArray[i] CGPointValue];
        CGRect shouldRect = [self getBrushRectForPoint:tempPoint];
        if (CGRectIntersectsRect(rect, shouldRect)) {
            [[UIImage imageWithName:@"whiteBrush"] drawInRect:shouldRect];
        }
    }
}

@end
